<template>
  <div class="container">
    <el-form :model="form" ref="form" label-width="120px" :rules="rules" class="form-container">
      <el-form-item label="动态标题" prop="title">
        <el-input v-model="form.title" placeholder="请输入动态标题"></el-input>
      </el-form-item>
      <el-form-item label="作者" prop="author">
        <el-input v-model="form.author" placeholder="请输入作者"></el-input>
      </el-form-item>
      <el-form-item label="发布时间" prop="publishTime">
        <el-input v-model="form.publishTime" placeholder="请输入发布时间 (yyyy-MM-dd HH:mm:ss)"></el-input>
      </el-form-item>
      <el-form-item label="新闻图片" prop="newsImage">
        <el-upload
          class="upload-demo"
          action="http://localhost:1111/api/dynamics/upload"
          list-type="picture-card"
          :on-preview="handlePictureCardPreview"
          :on-remove="handleRemove"
          :file-list="fileList"
          :on-success="handleUploadSuccess"
        >
          <i class="el-icon-plus"></i>
        </el-upload>
        <el-dialog v-model="dialogVisible">
          <img width="100%" :src="dialogImageUrl" alt="" />
        </el-dialog>
      </el-form-item>
      <el-form-item label="关键字" prop="keywords">
        <el-input v-model="form.keywords" placeholder="请设置该分类的关键词，以空格分开，最多5个！"></el-input>
      </el-form-item>
      <el-form-item label="动态简介" prop="newsIntro">
        <el-input type="textarea" v-model="form.newsIntro" maxlength="300" show-word-limit placeholder="请输入分类描述内容"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleSubmit">提交</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script lang="ts">
import { defineComponent, ref } from 'vue';
import axios from 'axios';
import { ElMessage } from 'element-plus';
import { useRouter } from 'vue-router';

export default defineComponent({
  name: 'FieldCreate',
  setup(_, { emit }) {
    const form = ref({
      title: '',
      author: '',
      publishTime: '',
      newsImage: '',
      keywords: '',
      newsIntro: ''
    });

    const router = useRouter();
    
    const rules = {
      title: [{ required: true, message: '动态标题不能为空', trigger: 'blur' }],
      author: [{ required: true, message: '作者不能为空', trigger: 'blur' }],
      publishTime: [{ required: true, message: '发布时间不能为空', trigger: 'blur' }],
      newsImage: [{ required: true, message: '新闻图片不能为空', trigger: 'change' }],
      newsIntro: [{ required: true, message: '动态简介不能为空', trigger: 'blur' }]
    };

    const fileList = ref([]);
    const dialogVisible = ref(false);
    const dialogImageUrl = ref('');

    const handlePictureCardPreview = (file: any) => {
      dialogImageUrl.value = file.url;
      dialogVisible.value = true;
    };

    const handleRemove = (file: any, fileList: any) => {
      form.value.newsImage = '';
    };

    const handleUploadSuccess = (response: any, file: any) => {
      if (response.success && response.data && response.data.url) {
        form.value.newsImage = response.data.url;
      } else {
        console.error('上传成功，但未找到图片URL');
      }
    };

    const validatePublishTime = (publishTime: string) => {
      const regex = /^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/;
      return regex.test(publishTime);
    };

    const handleSubmit = async () => {
      if (!validatePublishTime(form.value.publishTime)) {
        ElMessage.error('您输入的发布时间格式有误，请重新输入');
        return;
      }

      try {
        const response = await axios.post('http://localhost:1111/api/dynamics', {
          dynamic: {
            title: form.value.title,
            author: form.value.author,
            publishTime: form.value.publishTime,
            newsImage: form.value.newsImage || 'default_image_url',
            keywords: form.value.keywords,
            newsIntro: form.value.newsIntro
          }
        });
        emit('dynamicCreated', response.data);

        form.value = {
          title: '',
          author: '',
          publishTime: '',
          newsImage: '',
          keywords: '',
          newsIntro: ''
        };
        fileList.value = [];

        router.push('/fielddetail');
      } catch (error) {
        console.error('创建动态时出错:', error);
      }
    };

    return {
      form,
      rules,
      fileList,
      dialogVisible,
      dialogImageUrl,
      handlePictureCardPreview,
      handleRemove,
      handleUploadSuccess,
      handleSubmit,
    };
  }
});
</script>

<style scoped>
.container {
  padding: 20px;
  max-width: 1000px;
  margin: 60px auto 0 auto;
  background: #b5c6df;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.form-container {
  padding: 20px;
}

.el-form-item {
  margin-bottom: 20px;
}

.el-input, .el-textarea {
  width: 100%;
}

.upload-demo .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 100%;
  max-width: 300px;
}

.upload-demo .el-upload:hover {
  border-color: #409eff;
}

.upload-demo img {
  width: 100px;
  height: 100px;
}

.el-button {
  width: 100%;
  max-width: 200px;
  margin: 0 auto;
  display: block;
}

.el-dialog__wrapper {
  width: 90%;
  max-width: 600px;
  margin: 0 auto;
}

.el-dialog {
  width: 100%;
}

</style>
